﻿using AutoMapper;
using MediatR;
using RBAC.Domain.SmartHealthcare.Hosiptial;
using RBAC.Domain.SmartHealthcare;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using SmartHealthcare.Read.Api.Application.Command.PatientList;
using SmartHealthcare.Read.Api.DTo;

namespace SmartHealthcare.Read.Api.Application.Handler.PatientList
{
    /// <summary>
    /// 获取病人列表处理器
    /// </summary>
    public class GetPatientListHandler : IRequestHandler<GetPatientListCommand, APIResult<List<PatientListDto>>>
    {
        private readonly IBaseRepository<PatientListModel> patientRepository;
        private readonly IBaseRepository<InpatientRegistryModel> inpatientRegistryRepository;
        private readonly IBaseRepository<DepartmentModel> departmentRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetPatientListHandler> logger;

        public GetPatientListHandler(
            IBaseRepository<PatientListModel> patientRepository,
            IBaseRepository<InpatientRegistryModel> inpatientRegistryRepository,
            IBaseRepository<DepartmentModel> departmentRepository,
            IMapper mapper,
            ILogger<GetPatientListHandler> logger)
        {
            this.patientRepository = patientRepository;
            this.inpatientRegistryRepository = inpatientRegistryRepository;
            this.departmentRepository = departmentRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        /// <summary>
        /// 获取病人列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<List<PatientListDto>>> Handle(GetPatientListCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<PatientListDto>> res = new APIResult<List<PatientListDto>>();

            try
            {
                logger.LogInformation($"开始查询病人列表，查询条件：MedicalCard={request.MedicalCard}, PatientName={request.PatientName}, DepartmentId={request.DepartmentId}, WardNo={request.WardNo}");

                // 获取所有未删除的病人、住院登记记录和科室记录
                var allPatientsQuery = patientRepository.GetALL().Where(x => x.IsDeleted == false);
                var allInpatientRegistriesQuery = inpatientRegistryRepository.GetALL().Where(x => x.IsDeleted == false);
                var allDepartmentsQuery = departmentRepository.GetALL().Where(x => x.IsDeleted == false);
                
                // 执行查询并获取结果
                var allPatients = await Task.Run(() => allPatientsQuery.ToList());
                var allInpatientRegistries = await Task.Run(() => allInpatientRegistriesQuery.ToList());
                var allDepartments = await Task.Run(() => allDepartmentsQuery.ToList());
                
                logger.LogInformation($"数据库中总共有{allPatients.Count}个未删除的病人，{allInpatientRegistries.Count}个住院登记记录，{allDepartments.Count}个科室记录");

                // 输出病人数据详情
                logger.LogInformation("=== 病人数据详情 ===");
                foreach (var patient in allPatients.Take(5)) // 只显示前5个
                {
                    logger.LogInformation($"病人ID: {patient.Id}, 姓名: {patient.Name}, 医疗卡号: {patient.MedicalCard}, 身份证号: {patient.IdCard}");
                }
                if (allPatients.Count > 5)
                {
                    logger.LogInformation($"... 还有{allPatients.Count - 5}个病人");
                }

                // 输出住院登记数据详情
                logger.LogInformation("=== 住院登记数据详情 ===");
                foreach (var registry in allInpatientRegistries.Take(5)) // 只显示前5个
                {
                    logger.LogInformation($"登记ID: {registry.Id}, 医疗卡号: {registry.MedicalCard}, 科室ID: {registry.DepartmentId}, 病房号: {registry.WardNo}");
                }
                if (allInpatientRegistries.Count > 5)
                {
                    logger.LogInformation($"... 还有{allInpatientRegistries.Count - 5}个住院登记");
                }

                // 创建结果列表
                var resultList = new List<PatientListDto>();

                // 基础的三表联查（病人表、住院登记表、科室表）
                var baseQuery = from patient in allPatients
                               join registry in allInpatientRegistries on patient.MedicalCard equals registry.MedicalCard
                               join department in allDepartments on registry.DepartmentId equals department.Id into deptJoin
                               from department in deptJoin.DefaultIfEmpty()
                               select new { Patient = patient, Registry = registry, Department = department };

                logger.LogInformation($"基础三表联查找到{baseQuery.Count()}条记录");

                // 根据查询条件筛选
                if (!string.IsNullOrWhiteSpace(request.MedicalCard))
                {
                    logger.LogInformation("=== 通过病人卡号筛选 ===");
                    baseQuery = baseQuery.Where(x => x.Patient.MedicalCard.Contains(request.MedicalCard) || x.Patient.IdCard.Contains(request.MedicalCard));
                    logger.LogInformation($"添加病人卡号筛选条件：{request.MedicalCard}");
                }

                if (!string.IsNullOrWhiteSpace(request.PatientName))
                {
                    logger.LogInformation("=== 通过病人姓名筛选 ===");
                    baseQuery = baseQuery.Where(x => x.Patient.Name.Contains(request.PatientName));
                    logger.LogInformation($"添加病人姓名筛选条件：{request.PatientName}");
                }

                if (request.DepartmentId.HasValue)
                {
                    logger.LogInformation("=== 通过科室ID筛选 ===");
                    baseQuery = baseQuery.Where(x => x.Registry.DepartmentId == request.DepartmentId.Value);
                    logger.LogInformation($"添加科室ID筛选条件：{request.DepartmentId.Value}");
                }

                if (request.WardNo.HasValue)
                {
                    logger.LogInformation("=== 通过病房号筛选 ===");
                    baseQuery = baseQuery.Where(x => x.Registry.WardNo == request.WardNo.Value);
                    logger.LogInformation($"添加病房号筛选条件：{request.WardNo.Value}");
                }

                // 执行查询
                var results = baseQuery.ToList();
                logger.LogInformation($"最终查询结果：{results.Count}条记录");

                // 转换为DTO
                foreach (var result in results)
                {
                    var patientDto = mapper.Map<PatientListDto>(result.Patient);
                    
                    // 填充住院登记信息
                    patientDto.InpatientRegistryId = result.Registry.Id;
                    patientDto.DepartmentId = result.Registry.DepartmentId;
                    patientDto.WardNo = result.Registry.WardNo;
                    patientDto.WardId = result.Registry.WardId;
                    patientDto.AdvancePayment = result.Registry.AdvancePayment;
                    patientDto.DiseaseDescription = result.Registry.DiseaseDescription;
                    patientDto.DrugContraindications = result.Registry.DrugContraindications;
                    patientDto.AdmissionTime = result.Registry.AdmissionTime;
                    patientDto.DischargeStatus = result.Registry.Discharge_status;
                    
                    // 填充科室信息
                    patientDto.DepartmentName = result.Department?.DepartmentName ?? string.Empty;
                    
                    resultList.Add(patientDto);
                    
                    // 输出查询到的记录详情
                    logger.LogInformation($"查询到记录：病人ID={result.Patient.Id}, 姓名={result.Patient.Name}, 医疗卡号={result.Patient.MedicalCard}, 住院登记ID={result.Registry.Id}, 科室ID={result.Registry.DepartmentId}, 科室名称={patientDto.DepartmentName}, 病房号={result.Registry.WardNo}");
                }

                res.Data = resultList;
                res.Code = APIEnums.Success;
                res.Msg = "查询成功";
                logger.LogInformation($"查询病人成功，共查询到{resultList.Count}条记录");
            }
            catch (Exception ex)
            {
                res.Code = APIEnums.Fail;
                res.Msg = "查询病人失败";
                logger.LogError(ex, "查询病人时发生异常：{Message}", ex.Message);
                logger.LogError(ex, "异常堆栈：{StackTrace}", ex.StackTrace);
            }

            return res;
        }



    }
}
